package com.csun.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.csun.dao.BaseDao;
import com.csun.entity.PageBean;
import com.csun.entity.Role;
import com.csun.entity.RoleRole;
import com.csun.service.RoleService;
import com.csun.util.StrUtil;

/**
 * @ClassName: RoleServiceImpl.java
 * @Description:TODO
 * @author danjinsong danjingsong@dragonwake.cn
 * @date 2017年2月17日下午7:57:41
 * 
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService{

	@Autowired
	private BaseDao<Role> roleDao;
	
	@Autowired
	private BaseDao<RoleRole> roleRoleDao;
	
	@Override
	public void save(Role role) {
		roleDao.saveOrUpdate(role);					//保存当前role
		Role serverRole = 
				roleDao.get("from Role r where r.roleName = ?"
						, new Object[]{"社区服务者"});	//查找服务者角色
		RoleRole roleRole = new RoleRole();
		roleRole.setFaRole(serverRole);				//父角色为 --服务角色
		roleRole.setSonRole(role);					//子角色为 --当前角色
		roleRoleDao.save(roleRole);					//保存当前映射关系
	}

	@Override
	public void delete(Role role) {
		roleDao.delete(role);
	}

	@Override
	public void delete(Integer id) {
		Role role = new Role();
		role.setRoleId(id);
		roleDao.delete(role);
	}

	@Override
	public Role get(Role s_role) {
		StringBuffer hql = new StringBuffer("from Role r ");
		if(s_role != null){
			if(StrUtil.isNotEmpty(s_role.getRoleName())){
				hql.append(" and r roleName like '%"+s_role.getRoleName()+"%'");
			}
		}
		return roleDao.get(hql.toString().replaceFirst(" and ", " where "), new Object[]{});
	}
	
	@Override
	public Role get(Integer id) {
		return roleDao.get(Role.class, id);
	}
	
	@Override
	public List<Role> find(Role s_role, PageBean pagebean) {
		StringBuffer hql = new StringBuffer("from Role r ");
		if(s_role != null){
			if(StrUtil.isNotEmpty(s_role.getRoleName())){
				hql.append(" and r roleName like '%"+s_role.getRoleName()+"%'");
			}
		}
		if(pagebean != null)
			return roleDao.find(hql.toString().replaceFirst(" and ", " where "), new Object[]{},pagebean);
		return roleDao.find(hql.toString().replaceFirst(" and ", " where "), new Object[]{});
	}

	@Override
	public Long count(Role s_role) {
		StringBuffer hql = new StringBuffer("select count(*) as total from Role r ");
		if(s_role != null){
			if(StrUtil.isNotEmpty(s_role.getRoleName())){
				hql.append(" and r roleName like '%"+s_role.getRoleName()+"%'");
			}
		}
		return roleDao.count(hql.toString().replaceFirst(" and ", " where "), new Object[]{});
	}
}
